package cn.itcast.service.impl;

import cn.itcast.dao.Company;
import cn.itcast.factory.MapperFactory;
import cn.itcast.mapper.CompanyMapper;
import cn.itcast.service.CompanyService;
import cn.itcast.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CompanyServiceImpl implements CompanyService {
    private  SqlSession sqlSession = null;
    private CompanyMapper mapper = null;
    @Override
    public List<Company> findAll(int pageNum) {
        sqlSession = MapperFactory.getSqlSession();
        mapper = MapperFactory.getMapper(sqlSession, CompanyMapper.class);
        PageHelper.startPage(pageNum,10);
        List<Company> list = mapper.findAll();
        TransactionUtil.close(sqlSession);
        return list;
    }

    @Override
    public Company toEdit(String id) {
        sqlSession = MapperFactory.getSqlSession();
        mapper = MapperFactory.getMapper(sqlSession, CompanyMapper.class);
        Company company = mapper.toEdit(id);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
        return company;
    }

    @Override
    public void edit(Company company) {
        sqlSession = MapperFactory.getSqlSession();
        mapper = MapperFactory.getMapper(sqlSession, CompanyMapper.class);
        mapper.edit(company);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void save(Company company) {
        sqlSession = MapperFactory.getSqlSession();
        mapper = MapperFactory.getMapper(sqlSession, CompanyMapper.class);
        mapper.save(company);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void deleteById(String id) {
        sqlSession = MapperFactory.getSqlSession();
        mapper = MapperFactory.getMapper(sqlSession, CompanyMapper.class);
        mapper.deleteById(id);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }
}
